package com.yaxin.outsourcing.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yaxin.common.excel.ExcelListener;
import com.yaxin.common.excel.ExcelResult;
import com.yaxin.common.exception.ServiceException;
import com.yaxin.common.helper.LoginHelper;
import com.yaxin.common.utils.ValidatorUtils;
import com.yaxin.common.utils.spring.SpringUtils;
import com.yaxin.outsourcing.domain.vo.OutSourcingPersonImportVO;
import com.yaxin.outsourcing.domain.po.AccessApplication;
import com.yaxin.outsourcing.domain.po.OutsourcingPerson;
import com.yaxin.outsourcing.enums.PersonStatus;
import com.yaxin.outsourcing.mapper.AccessApplicationMapper;
import com.yaxin.outsourcing.mapper.OutsourcingPersonMapper;
import com.yaxin.outsourcing.service.IAccessApplicationService;
import com.yaxin.outsourcing.service.IOutsourcingPersonService;
import com.yaxin.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class OutSourcingPersonImportListener extends AnalysisEventListener<OutSourcingPersonImportVO> implements ExcelListener<OutSourcingPersonImportVO> {

    private final ISysUserService userService;

    private IOutsourcingPersonService outsourcingPersonService;
    private IAccessApplicationService accessApplicationService;

    private final String operName;

    private final Boolean isUpdateSupport;

    @Autowired
    private OutsourcingPersonMapper outsourcingPersonMapper;
    @Autowired
    private AccessApplicationMapper accessApplicationMapper;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public OutSourcingPersonImportListener(Boolean isUpdateSupport) {
        this.userService = SpringUtils.getBean(ISysUserService.class);
        this.outsourcingPersonService = SpringUtils.getBean(IOutsourcingPersonService.class);
        this.accessApplicationService = SpringUtils.getBean(IAccessApplicationService.class);
        this.outsourcingPersonMapper = SpringUtils.getBean(OutsourcingPersonMapper.class);
        this.accessApplicationMapper = SpringUtils.getBean(AccessApplicationMapper.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void invoke(OutSourcingPersonImportVO userImportVo, AnalysisContext context) {
        System.out.println("导入数据" + userImportVo.getIdCard());
        Long appNO = userImportVo.getAppNo();
        Long appId = accessApplicationService.getBaseMapper().selectOne(
            new LambdaQueryWrapper<AccessApplication>()
                .eq(AccessApplication::getAppNo, appNO)
        ).getId();
        OutsourcingPerson user = this.outsourcingPersonService.selectByIdCard(userImportVo.getIdCard());
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(user)) {
                user = BeanUtil.toBean(userImportVo, OutsourcingPerson.class);
                user.setCreatedBy(this.operName);
                user.setUpdatedBy(this.operName);
                Long userId = (Long) outsourcingPersonService.getBaseMapper().selectObjs(
                    new QueryWrapper<OutsourcingPerson>()
                        .select("MAX(per_id)")
                ).get(0) + 1;
                user.setPerId(userId);
                user.setAppId(appId);
                user.setStatus(PersonStatus.NORMAL);
                ValidatorUtils.validate(user);
                //检查人数是否超限
                checkPersonCountLimit(appId);
                outsourcingPersonService.getBaseMapper().insert(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、人员 ").append(user.getUserName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long userId = (Long) outsourcingPersonService.getBaseMapper().selectObjs(
                    new QueryWrapper<OutsourcingPerson>()
                        .select("MAX(per_id)")
                ).get(0) + 1;
                user = BeanUtil.toBean(userImportVo, OutsourcingPerson.class);
                user.setPerId(userId);
                user.setAppId(appId);
                user.setUpdatedBy(this.operName);
                user.setStatus(PersonStatus.NORMAL);
                ValidatorUtils.validate(user);
//                userService.checkUserAllowed(user);
//                userService.checkUserDataScope(user.getUserId());
//                user.setUpdateBy(userImportVo.);
                outsourcingPersonService.getBaseMapper().updateById(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、人员 ").append(user.getUserName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、人员 ").append(user.getUserName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、人员 " + user.getUserName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<OutSourcingPersonImportVO> getExcelResult() {
        return new ExcelResult<OutSourcingPersonImportVO>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<OutSourcingPersonImportVO> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }

    public void checkPersonCountLimit(Long appId) {
        if (appId == null) {
            return; // 如果appId为空则不检查
        }

        // 1. 查询申请单
        AccessApplication application = accessApplicationMapper.selectById(appId);
        if (application == null) {
            throw new RuntimeException("申请单不存在");
        }

        // 2. 查询当前人员数量
        long currentPersonCount = outsourcingPersonMapper.selectCount(
            new LambdaQueryWrapper<OutsourcingPerson>()
                .eq(OutsourcingPerson::getAppId, appId)
                .eq(OutsourcingPerson::getIsDeleted, 0) // 只统计未删除的
        );

        // 3. 检查是否超限
        if (currentPersonCount >= application.getEntryCount()) {
            throw new RuntimeException("外协人员数量已超过申请人数限制");
        }
    }
}
